package com.common.exception;


import java.io.IOException;
import java.sql.SQLException;

import com.common.enums.ErrorCode;
import com.common.response.BaseResponse;
import com.common.response.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/** 全局异常处理器 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

  @ExceptionHandler(BusinessException.class)
  public BaseResponse<?> businessExceptionHandler(BusinessException e) {
    log.error("businessException: " + e.getMessage(), e);
    return ResultUtils.error(e.getCode(), e.getMessage());
  }

  /**
   * 运行时异常处理
   *
   * @param e
   * @return
   */
  @ExceptionHandler(RuntimeException.class)
  public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
    log.error("runtimeException", e);
    return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
  }

  /**
   * sql异常处理
   *
   * @param e
   * @return
   */
  @ExceptionHandler(SQLException.class)
  public BaseResponse<?> handleSqlException(SQLException e) {
    log.error("SQLException", e);
    return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
  }

  /**
   * IO异常处理
   *
   * @param e
   * @return
   */
  @ExceptionHandler(IOException.class)
  public BaseResponse<?> handleIOException(IOException e) {
    log.error("IOException", e);
    return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
  }
}
